package com.norra.client.ui

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.norra.base.utils.Toaster
import com.norra.client.App
import com.norra.client.R
import com.norra.client.viewmodel.LoginViewModel
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseActivity(), View.OnClickListener {

    private lateinit var viewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        btn_login.setOnClickListener(this)
        btn_get_code.setOnClickListener(this)
        btn_forgot_pwd.setOnClickListener(this)
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
    }

    private fun login() {
        var phone = edit_phone.text.toString()
        val pwd = edit_pwd.text.toString()

        if (phone.isEmpty()) {
            Toaster.shortToast("Input phone number")
            return
        }
        if (pwd.isEmpty()) {
            Toaster.shortToast("Input password")
            return
        }

        phone = getTelCountry() + phone;

        showLoadingView()
        viewModel.login(phone, pwd).observe(this, Observer {
            hideLoadingView()
            if (it.isSuccess) {
                App.get().saveUserToken(it.data!!.token!!)
                startActivity(Intent(this, MainActivity::class.java))
                finish()
            }
        })
    }

    private fun getTelCountry(): String {
//        return "86-";
        return "";
    }

    private fun getVerifyCode() {
        val phone = edit_phone.text.toString()
        if (phone.isEmpty()) {
            Toaster.shortToast("Input phone number")
            return
        }
        showLoadingView()
        viewModel.getVerifyCode(phone).observe(this, Observer {
            hideLoadingView()
            if (it.isSuccess) {
                btn_get_code.isEnabled = false
                Toaster.shortToast("Get new password success")
            } else {
                Toaster.shortToast("Get new password fail")
            }
        })
    }

    override fun onClick(v: View?) {
        when {
            v!!.id == R.id.btn_login -> {
                login()
            }
            v.id == R.id.btn_get_code -> {
                getVerifyCode()
            }
            v.id == R.id.btn_forgot_pwd -> {
                btn_get_code.visibility = View.VISIBLE
            }
        }
    }
}